package cn.steel.service.impl;

import cn.steel.domain.dto.InventoryUpdateDto;
import cn.steel.domain.entity.InventoryAnalysis;
import cn.steel.domain.entity.Order;
import cn.steel.domain.vo.OrderItemVo;
import cn.steel.domain.vo.OrderListVo;
import cn.steel.mapper.*;
import cn.steel.service.OrderService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import cn.steel.domain.dto.OrderDto;
import cn.steel.domain.dto.OrderItemDto;
import cn.steel.domain.entity.Order;
import cn.steel.domain.entity.OrderItem;
import cn.steel.domain.vo.OrderDetailVo;
import cn.steel.domain.vo.OrderListVo;
import cn.steel.utils.BusinessException;
import cn.steel.mapper.OrderMapper;
//import cn.steel.service.InventoryService;
import cn.steel.service.OrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service

public class OrderServiceImpl implements OrderService {
    @Lazy
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private  OrderMapper orderMapper;
    @Resource
    private ProductMapper productMapper;
    @Autowired
    private  InventoryAnalysisMapper inventoryMapper;
    @Override
    public List<Order> findOrdersByBuyerId(Long buyerId) {
        return orderMapper.findByBuyerId(buyerId);
    }

    @Override
    public long countOrdersBySupplierId(Long supplierId) {
        return orderMapper.countOrdersBySupplierId(supplierId);

    }

    private static final Logger log = LogManager.getLogger(OrderServiceImpl.class);

    @Override
    @Transactional
    public Order createOrder(OrderDto orderDto) {
        Order order = new Order();
        BeanUtils.copyProperties(orderDto, order);

        // 生成订单号
        String orderNo = generateOrderNo();
        order.setOrderNo(orderNo);
        order.setStatus("PENDING");
        order.setCreateTime(new Date());

        orderMapper.insert(order);

        // 保存订单项
        for (OrderItemDto itemDto : orderDto.getItems()) {
            OrderItem item = new OrderItem();
            BeanUtils.copyProperties(itemDto, item);
            item.setOrderId(order.getId());
            orderItemMapper.insert(item);
        }

        return order; // 返回 Order 对象
    }



    @Override
    @Transactional
    public boolean cancelOrder(String orderNo, Long userId) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null) {
            log.error("订单不存在: {}", orderNo);
            return false;
        }
        if (order.getBuyerId().equals(userId) && "PENDING".equals(order.getStatus())) {
            order.setStatus("CANCELLED");
            orderMapper.update(order);
            return true;
        }
        return false;
    }
    @Override
    @Transactional
    public boolean confirmReceipt(String orderNo, Long userId) {
        log.info("开始处理订单确认收货, 订单号: {}, 用户ID: {}", orderNo, userId);

        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null) {
            log.error("订单不存在: {}", orderNo);
            return false;
        }

        if (!order.getBuyerId().equals(userId)) {
            log.error("用户{}无权限确认订单{}", userId, orderNo);
            return false;
        }

        if (!"SHIPPED".equals(order.getStatus())) {
            log.error("订单状态{}不符合确认收货要求", order.getStatus());
            return false;
        }

        order.setStatus("COMPLETED");
        order.setCompleteTime(new Date());
        int updated = orderMapper.update(order);

        if (updated > 0) {
            log.info("订单{}确认收货成功", orderNo);
            return true;
        } else {
            log.error("订单{}确认收货失败，数据库更新未生效", orderNo);
            return false;
        }
    }

    @Override
    public List<OrderListVo> getSupplierOrderList(Long supplierId, String status, String orderNo) {
        // 如果有订单号，优先按订单号精确查询
        if (orderNo != null && !orderNo.isEmpty()) {
            OrderDetailVo detail = orderMapper.selectSupplierOrderDetail(orderNo, supplierId);
            return detail != null ? List.of(convertToOrderListVo(detail)) : List.of();
        }
        // 否则按状态筛选
        return orderMapper.selectSupplierOrderList(supplierId, status);
    }

    private OrderListVo convertToOrderListVo(OrderDetailVo detail) {
        OrderListVo vo = new OrderListVo();
        BeanUtils.copyProperties(detail, vo);
        return vo;
    }
    @Override
    public OrderDetailVo getSupplierOrderDetail(String orderNo, Long supplierId) {
        return orderMapper.selectSupplierOrderDetail(orderNo, supplierId);
    }
    @Override
    @Transactional
    public boolean shipOrder(String orderNo, String shippingCompany, String trackingNumber, String shippingAddress,Long supplierId) {
        OrderDetailVo detail = orderMapper.selectSupplierOrderDetail(orderNo, supplierId);
        if (detail == null) {
            log.error("订单详情不存在: {}", orderNo);
            return false;
        }

        // 添加buyerId检查
        if (detail.getBuyerId() == null) {
            log.error("订单{}的买家ID为空", orderNo);
            return false;
        }

        if ("PAID".equals(detail.getStatus())) {
            orderMapper.updateOrderStatus(orderNo, "SHIPPED");
            orderMapper.updateShippingInfo(orderNo, shippingCompany,trackingNumber, shippingAddress);
        }
        return false;
    }


    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6).toUpperCase();
    }



    @Override
    @Transactional
    public void deleteSupplierOrder(String orderNo, Long supplierId) {
        int affected = orderMapper.deleteSupplierOrder(orderNo, supplierId);
        if (affected == 0) {
            throw new BusinessException("删除失败，订单不存在或无权限");
        }
    }


    public OrderDetailVo getOrderDetail(String orderNo, Long userId) {
        Order order = orderMapper.getOrderByOrderNo(orderNo);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        if (!order.getBuyerId().equals(userId)) {
            throw new BusinessException("无权查看此订单");
        }
        return orderMapper.selectOrderDetail(orderNo, userId);
    }

    @Override
    public PageInfo<OrderListVo> getPagedOrderList(Long userId, String status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<OrderListVo> list = orderMapper.selectOrderList(userId, status);
        return new PageInfo<>(list);
    }



    @Override
    public PageInfo<OrderListVo> getSupplierOrderList(Long supplierId, String status, String orderNo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        // 如果有订单号，优先按订单号精确查询
        if (orderNo != null && !orderNo.isEmpty()) {
            OrderDetailVo detail = orderMapper.selectSupplierOrderDetail(orderNo, supplierId);
            List<OrderListVo> list = detail != null ? List.of(convertToOrderListVo(detail)) : List.of();
            return new PageInfo<>(list);
        }

        // 否则按状态筛选
        List<OrderListVo> list = orderMapper.selectSupplierOrderList(supplierId, status);
        return new PageInfo<>(list);
    }

    @Override
    public void deleteOrder(String orderNo) {
        orderMapper.deleteOrderByOrderNo(orderNo);
    }



    @Override
    @Transactional
    public boolean reduceInventory(InventoryUpdateDto dto) {
        // 检查库存是否充足
        InventoryAnalysis inventory = inventoryMapper.selectByProduct(dto.getProductId());
        if (inventory == null || inventory.getInventory() < dto.getQuantity()) {
            return false;
        }
        // 计算新的库存量
        int newInventory = inventory.getInventory() - dto.getQuantity();

        // 直接更新product和inventory_analysis表
        int affectedRows = productMapper.updateProductInventory(
                dto.getProductId(),
                dto.getQuantity());

        return affectedRows > 0;
    }



}